import { getBaseUrl, requestUtil, getWxLogin, getUserProfile, requestPay } from '../../utils/requestUtil.js'
import regeneratorRuntime from "../../lib/runtime/runtime"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    baseUrl: '',
    totalPrice: 0,
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const baseUrl = getBaseUrl();
    this.setData({
      baseUrl
    })
  },

  async handleOrderPay() {
  //  let res = await getWxLogin()
  //  console.log(res.code)

  //  let res2 = await getUserProfile()
  //  console.log(res2.userInfo.nickName, res2.userInfo.avatarUrl)

    const token = wx.getStorageSync('token')
    if(!token) {
      Promise.all([getWxLogin(), getUserProfile()]).then((res) => {
        console.log(res[0].code, res[1].userInfo.nickName, res[1].userInfo.avatarUrl)
        let loginParam = {
          code: res[0].code,
          nickName: res[1].userInfo.nickName,
          avatarUrl: res[1].userInfo.avatarUrl
        }
        console.log(loginParam)
        wx.setStorageSync('userInfo', res[1].userInfo)
        this.wxlogin(loginParam)
      })
    } else {
      console.log("token存在: " + token);
      console.log('支付继续，创建订单')
      this.createOrder()
    }
  },

  async createOrder() {
    try{
      const totalPrice = this.data.totalPrice 
      const address = this.data.address.provinceName+this.data.address.cityName+this.data.address.countyName+this.data.address.detailInfo
      const consignee = this.data.address.userName
      const telNumber = this.data.address.telNumber
      let goods = []
      this.data.cart.forEach(item => goods.push({
        goodsId: item.id,
        goodsNumber: item.num,
        goodsPrice: item.price,
        goodsName: item.name,
        goodsPic: item.proPic
      }))
      const orderParam = {
        totalPrice,
        address,
        consignee,
        telNumber,
        goods
      }
      const res = await requestUtil({
        url: '/my/order/create',
        method: 'POST',
        data: orderParam
      })
      console.log("orderNo: " + res.orderNo)
      const orderNo = res.orderNo

      // 调用统一下单预支付
      const preparePayRes = await requestUtil({
        url: '/my/order/preparePay',
        method: 'POST',
        data: orderNo
      })
      let payRes = await requestPay(preparePayRes)

      // 删除缓存中已经支付的商品
      let newCart = wx.getStorageSync('cart')
      newCart = newCart.filter(item => !item.checked)
      wx.setStorageSync('cart', newCart)

      wx.showToast({
        title: '支付成功',
        icon: 'none'
      })

      wx.navigateTo({
        url: '/pages/order/index?type=0',
      })
    }catch(error){
      console.log(error)
      wx.showToast({
        title: '支付失败，请稍后重试',
        icon: 'none'
      })
    }
  },

  async wxlogin(loginParam) {
    const result = await requestUtil({
      url: '/user/wxlogin',
      data: loginParam,
      method: 'post'
    })
    console.log(result)
    const token = result.token
    if (result.code === 0) {
      wx.setStorageSync('token', token)
      console.log('支付继续，创建订单')
      this.createOrder()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const address = wx.getStorageSync('address')
    let cart = wx.getStorageSync('cart') || []

    cart = cart.filter(item => item.checked)

    let totalPrice = 0
    let totalNum = 0
    cart.forEach(item => {
      totalNum += item.num
      totalPrice += item.price * item.num
    })
    this.setData({
      cart,
      totalNum,
      totalPrice,
      address
    })
  }
})